﻿using System;
using System.Linq;
using Volo.Abp;

namespace Shared.Service.DataPermissions
{
    public class SourceDataPermission : DataPermission<string, SourceDataPermission>
    {
        /// <summary>
        /// 没启用的
        /// </summary>
        public static readonly SourceDataPermission Disable = new SourceDataPermission(DataPermissionState.Disable);

        /// <summary>
        /// Null 的项目数据范围内为
        /// </summary>
        public static readonly SourceDataPermission Null = new SourceDataPermission(DataPermissionState.Null);

        /// <summary>
        /// 所有的项目
        /// </summary>
        public static readonly SourceDataPermission All = new SourceDataPermission(DataPermissionState.All);

        /// <summary>
        /// 
        /// </summary>
        /// <param name="state"></param>
        protected SourceDataPermission(DataPermissionState state) : base(state)
        {

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sourceIds"></param>
        public SourceDataPermission(string[] sourceIds)
            : base(sourceIds)
        {

        }

        /// <summary>
        /// 以当前数据权限为基础，产生一个新的数据权限，
        /// 考虑用户输入的权限 默认交集计算  TODO 带抽象出通用方法
        /// </summary>
        /// <param name="inputIds"></param>
        /// <param name="disableAs">DisableAs 处理方式</param>
        /// <returns></returns>
        public override SourceDataPermission GetInputDataPermission(string[] inputIds,
            DisableAs disableAs = DisableAs.All)
        {
            Check.NotNullOrEmpty(inputIds, nameof(inputIds));

            switch (State)
            {
                case DataPermissionState.Disable:
                    return disableAs switch
                    {
                        DisableAs.All => new SourceDataPermission(inputIds),
                        _ => Null
                    };
                case DataPermissionState.Null:
                    return Null;
                case DataPermissionState.Normal:
                    var intersectIds = Ids.Intersect(inputIds).ToArray(); // 取交集
                    return intersectIds.Any() ? new SourceDataPermission(intersectIds) : Null;
                case DataPermissionState.All:
                    return new SourceDataPermission(inputIds);
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }
    }
}
